<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" :labelWidth="'125px'" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(76, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(76, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.customerNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:isFreecust="{ row, item }">
          <template v-if="!row.index">
            {{ row[item.prop] ? '是':'否' }}
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            v-for="item,index in formDatalists"
            :key="index"
            :label="item.name + ':'"
            :prop="item.type === 'Select'? item.selectValue : item.prop"
            class="w50p"
            :rules="item.isCheck ? rules[item.prop]:[
              { required: item.required, message: item.name + '不能为空', trigger: item.type === 'input'? 'blur' : 'change'}
            ]"
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="formData[ `${item.prop}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="formData[ `${item.selectValue}`]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
            >
              <el-option
                v-for="items,indexs in item.typeObj.list"
                :key="indexs"
                :label="items.name"
                :value="items.value"
              />
            </el-select>
            <el-date-picker
              v-if="item.type === 'TimePicker'"
              v-model="formData[ `${item.prop}`]"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="'选择' + item.name"
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import customerApi from "@/api/livestock-manage/sale-manage/customerManage";
import customerTypeApi from "@/api/livestock-manage/sale-manage/customerType";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: '客户名称',
          prop: 'customerName',
          type: 'input',
        },
        {
          label: '客户简称',
          prop: 'shortName',
          type: 'input',
        },
        {
          label: '客户类型',
          prop: 'customerTypeNo',
          type: 'select',
          options: [],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: "统一社会信用代码",
          prop: "creditCode",
          type: "input",
        },
        {
          label: "所属行业",
          prop: "trade",
          type: "input",
        },
      ],
      selectedStaffList: [],
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "customerName",
          typeObj: {},
          name: "客户名称",
          required: true
        },
        {
          type: "input",
          prop: "shortName",
          typeObj: {},
          name: "客户简称"
          // required: true
        },
        {
          type: "Select",
          prop: "customerTypeName",
          selectValue: "customerTypeNo",
          typeObj: {},
          name: "客户类型",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "creditCode",
          typeObj: {},
          name: "统一社会信用代码",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "trade",
          typeObj: {},
          name: "所属行业",
          // required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "isFreecust",
          selectValue: "isFreecust",
          typeObj: {
            list: [
              { name: "是", value: true },
              { name: "否", value: false }
            ]
          },
          name: "散户",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "legalBody",
          typeObj: {},
          name: "法人",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "address",
          typeObj: {},
          name: "企业地址",
          required: false
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "tel",
          typeObj: {},
          name: "电话",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "url",
          typeObj: {},
          name: "Web网址",
          required: false
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "email",
          typeObj: {},
          name: "e-mail地址",
          required: false,
          isCheck: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "country",
          typeObj: {},
          name: "国家/地区",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bank",
          typeObj: {},
          name: "开户行",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bankAccount",
          typeObj: {},
          name: "银行帐号",
          // required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "enableStatus",
          selectValue: "enableStatus",
          typeObj: {
            list: [
              { name: "是", value: true },
              { name: "否", value: false }
            ]
          },
          name: "是否启用",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          // required: true,
          notSearch: true
        }
      ],
      rules: {
        email: [
          {
            required: false,
            message: "邮箱地址不能为空",
            trigger: ["blur", "change"]
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    let list = []
    this.formDatalists.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px'
      }
      if (['enableStatus', 'isFreecust'].includes(el.prop)) {
        obj.slotName = 'isFreecust'
      }
      list.push(obj)
    })
    list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '150' })
    this.tableColumn = list

    this.search();
    this.getCustomerTypeList();
  },
  methods: {
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    getCustomerTypeList() {
      customerTypeApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          let list = [];
          // 提供表头搜索数据
          res.data.forEach(item => {
            list.push({
              name: item.customerTypeName,
              value: item.customerTypeNo
            });
          });
          this.setOptions(this.formConfig, 'customerTypeNo', list)
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "customerTypeName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: this.searchlist
      };
      customerApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.customerNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      customerApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          customerApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = {};
      this.nowChanceStau = "add";
      this.titleText = "添加客户";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      this.nowChanceStau = "edit";
      this.titleText = "修改客户";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            customerApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            customerApi.add(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 155px;
}
</style>
